package com.sinovatio.tls.zttbg.gate.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2017/12/1 0001.
 */
@Component
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * api网关拦截器进行权限校验
     * @return
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //解决跨域
        HttpServletResponse response = ctx.getResponse();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        response.setHeader("X-Powered-By","Jetty");

        //获取用户名密码进行验证
       // String username = request.getHeader("zttbg_username");
      //  String password = request.getHeader("zttbg_password");
         String username ="sinovation";
         String password ="test123";

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            sendFailResult(ctx,403,"null username or password!");
            return null;
        }

        if(!"sinovation".equals(username) || !"test123".equals(password)){
            sendFailResult(ctx,403,"wrong username or password");
            return null;
        }

        //这两句是获取请求地址和方法的，后续如果要做数据服务的权限控制，则在这里操作
        //final String requestUri = request.getRequestURI().toString();
        //final String method = request.getMethod();

        //这两句可以设置通用参数到每一个服务下
        //ctx.addZuulRequestHeader("authUserId",user.getId());
        //ctx.getRequest().setAttribute("authUser",user);

        //验证成功！！！
        ctx.setSendZuulResponse(true);// 对该请求进行路由
        ctx.setResponseStatusCode(200);

        return null;
    }


    /**
     * 返回错误信息
     * @param ctx
     * @param code
     */
    private void sendFailResult(RequestContext ctx, int code, String content){
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(code);
        ctx.setResponseBody(content);
    }


}
